'use strict';
var React = require('react');
var reactDom = require('react-dom/server');
var reactRedux = require('react-redux');
var configureStore = require('../public/javascripts/stores/index.js');
var HkfsProducts = require('../public/javascripts/containers/pc/HkfsProducts.jsx');
var Provider = reactRedux.Provider;
const store = configureStore();
var ModelRender = require('./modelRender.jsx');
var actions = require('../public/javascripts/actions/products');
var async = require('async');
var HttpOperate = require('../nodeLibrary/HttpOperate');
var httpOperate = new HttpOperate();
var backEndUrl = require('../nodeConfig/environmentConfig');
var httpOperateForHK = new HttpOperate(backEndUrl.hkBackEndUrl);

exports.RenderFunc = (renderCallBack,userId)=> {

    //根据后端返回的产品信息构造前端需要的数据结构
    function contructProductsGroup(type, typeName, result) {
        var regularProfitProduct = {
            type: type,
            typeName: typeName,
            productTypes: []
        };
        var resultContent = result.result;
        if (resultContent) {
            for (var i = 0; i < resultContent.length; i++) {
                var resultItem = {
                    name: resultContent[i].parName,
                    parId: resultContent[i].parId,
                    profit: resultContent[i].maxYearRate !== resultContent[i].minYearRate ? resultContent[i].minYearRate + '-' + resultContent[i].maxYearRate : resultContent[i].maxYearRate,
                    financingAmount: parseFloat(resultContent[i].financingAccount) > 10000 ? parseFloat(resultContent[i].financingAccount) / 10000 + '万' : resultContent[i].financingAccount + '元',
                    surplusAmount: parseFloat(resultContent[i].sraiseAccount) > 10000 ? parseFloat(resultContent[i].sraiseAccount) / 10000 + '万' : resultContent[i].sraiseAccount + '元',
                    process: (resultContent[i].yraiseAccount / resultContent[i].financingAccount * 100).toFixed(2) + '%',
                    products: []
                };
                for (var j = 0; j < resultContent[i].productResList.length; j++) {
                    var productResList = resultContent[i].productResList[j];
                    var product = [
                        {id: productResList.id, linkId: resultContent[i].parId},
                        productResList.name,
                        productResList.maxYearRate !== productResList.minYearRate ? productResList.minYearRate + '-' + productResList.maxYearRate : productResList.maxYearRate,
                        productResList.proTermStr,
                        parseFloat(productResList.sraiseAccount) > 10000 ? parseFloat(productResList.sraiseAccount) / 10000 + '万' : productResList.sraiseAccount + '元',
                        ((productResList.financingAccount - productResList.sraiseAccount) / productResList.financingAccount * 100).toFixed(2) + '%'
                    ];
                    resultItem.products.push(product);
                }
                regularProfitProduct.productTypes.push(resultItem);
            }
        }
        return regularProfitProduct;
    }

    async.parallel({

            //购买型浮动
            floatProfitProducts_1: (callBack)=> {
                var floatProfitProducts;
                callBack(null, floatProfitProducts);
              /*  httpOperate.httpPost('/pc/productInfoCtrl/getListByPar', {
                    'buyChannel': 2,
                    'curPage': 1,
                    'pageSize': 3,
               'userId':userId?userId:null
                }, (result)=> {
                    var regularProfitProduct = contructProductsGroup(0, '购买型', result);
                    if (regularProfitProduct.productTypes.length > 0) {
                        callBack(null, regularProfitProduct);
                    }
                    else {
                        callBack()
                    }
                })*/
            },
            //预约型浮动
            floatProfitProducts_2: (callBack)=> {
                var floatProfitProducts;
                callBack(null, floatProfitProducts);
               /* httpOperate.httpPost('/pc/productInfoCtrl/getListByPar', {
                    'buyChannel': 1,
                    'curPage': 1,
                    'pageSize': 3,
                'userId':userId?userId:null
                }, (result)=> {
                    var regularProfitProduct = contructProductsGroup(1, '预约型', result);
                    if (regularProfitProduct.productTypes.length > 0) {
                        callBack(null, regularProfitProduct);
                    }
                    else {
                        callBack()
                    }
                })*/
            },
            //预售型浮动
            floatProfitProducts_3: (callBack)=> {
                var floatProfitProducts;
                callBack(null, floatProfitProducts);
               /* httpOperate.httpPost('/pc/productInfoCtrl/getListByPar', {
                    'buyChannel': 4,
                    'curPage': 1,
                    'pageSize': 3,
                'userId':userId?userId:null
                }, (result)=> {
                    var regularProfitProduct = contructProductsGroup(2, '预售型', result);
                    if (regularProfitProduct.productTypes.length > 0) {
                        callBack(null, regularProfitProduct);
                    }
                    else {
                        callBack()
                    }
                })*/
            },

            //购买型固定+浮动
            regularAndFloatProfitProducts_1: (callBack)=> {
                var regularAndFloatProfitProducts;
                callBack(null, regularAndFloatProfitProducts);
                /*httpOperate.httpPost('/pc/productInfoCtrl/getListByPar', {
                    'buyChannel': 2,
                    'curPage': 1,
                    'pageSize': 3,
                 'userId':userId?userId:null
                }, (result)=> {
                    var regularProfitProduct = contructProductsGroup(0, '购买型', result);
                    if (regularProfitProduct.productTypes.length > 0) {
                        callBack(null, regularProfitProduct);
                    }
                    else {
                        callBack()
                    }
                })*/
            },
            //预约型固定+浮动
            regularAndFloatProfitProducts_2: (callBack)=> {
                var regularAndFloatProfitProducts;
                callBack(null, regularAndFloatProfitProducts);
                /*httpOperate.httpPost('/pc/productInfoCtrl/getListByPar', {
                    'buyChannel': 1,
                    'curPage': 1,
                    'pageSize': 3,
                 'userId':userId?userId:null
                }, (result)=> {
                    var regularProfitProduct = contructProductsGroup(1, '预约型', result);
                    if (regularProfitProduct.productTypes.length > 0) {
                        callBack(null, regularProfitProduct);
                    }
                    else {
                        callBack()
                    }
                })*/
            },
            //预售型固定+浮动
            regularAndFloatProfitProducts_3: (callBack)=> {
                var regularAndFloatProfitProducts;
                callBack(null, regularAndFloatProfitProducts);
               /* httpOperate.httpPost('/pc/productInfoCtrl/getListByPar', {
                    'buyChannel': 4,
                    'curPage': 1,
                    'pageSize': 3,
                'userId':userId?userId:null
                }, (result)=> {
                    var regularProfitProduct = contructProductsGroup(2, '预售型', result);
                    if (regularProfitProduct.productTypes.length > 0) {
                        callBack(null, regularProfitProduct);
                    }
                    else {
                        callBack()
                    }
                })*/
            },

            //基金，fundType:0其他类型,1,股票型, 2,债券型, 3,混合型,4,货币型,5,保本型,6,指数型,7,QDII,8	商品型
            hkfsProductRaisedFunds: (callBack)=> {
                var pageSize = 10;
                var curPage = 1;
                httpOperate.httpPost('/pc/fundCtrl/fundInfoList', {
                    'orderByType': 1,
                    'curPage': curPage,
                    'pageSize': pageSize
                }, (result)=> {
                    var realResult = [];
                    var resultContent = result.result;
                    if (resultContent) {
                        for (var i = 0; i < resultContent.length; i++) {
                            var resultItem = [
                                {id: resultContent[i].fundCode, linkId: resultContent[i].fundCode},
                                resultContent[i].fundFullName + '+' + resultContent[i].fundCode,
                                resultContent[i].nav,
                                resultContent[i].dayReturn,
                                resultContent[i].oneMonthReturn,
                                resultContent[i].quarterReturn,
                                resultContent[i].oneYearReturn,
                                resultContent[i].thisYearReturn
                            ];
                            realResult.push(resultItem);
                        }
                    }
                    var realResultObj = {
                        'totalPage': Math.ceil(result.size / pageSize),
                        'page': curPage,
                        'resultContent': realResult
                    };
                    store.dispatch(actions.receiveRaiseFunds(realResultObj));
                    callBack();
                });
            },
            //购买型固收
            regularProfitProducts_1: (callBack)=> {
                httpOperate.httpPost('/pc/productInfoCtrl/getListByPar', {
                    'buyChannel': 2,
                    'curPage': 1,
                    'pageSize': 3,
                    'userId':userId?userId:null
                }, (result)=> {
                    var regularProfitProduct = contructProductsGroup(0, '购买型', result);
                    if (regularProfitProduct.productTypes.length > 0) {
                        callBack(null, regularProfitProduct);
                    }
                    else {
                        callBack()
                    }
                })
            },
            //预约型固收
            regularProfitProducts_2: (callBack)=> {
                httpOperate.httpPost('/pc/productInfoCtrl/getListByPar', {
                    'buyChannel': 1,
                    'curPage': 1,
                    'pageSize': 3,
                    'userId':userId?userId:null
                }, (result)=> {
                    var regularProfitProduct = contructProductsGroup(1, '预约型', result);
                    if (regularProfitProduct.productTypes.length > 0) {
                        callBack(null, regularProfitProduct);
                    }
                    else {
                        callBack()
                    }
                })
            },
            //预售型固收
            regularProfitProducts_3: (callBack)=> {

                httpOperate.httpPost('/pc/productInfoCtrl/getListByPar', {
                    'buyChannel': 4,
                    'curPage': 1,
                    'pageSize': 3,
                    'userId':userId?userId:null
                }, (result)=> {
                    var regularProfitProduct = contructProductsGroup(2, '预售型', result);
                    if (regularProfitProduct.productTypes.length > 0) {
                        callBack(null, regularProfitProduct);
                    }
                    else {
                        callBack()
                    }
                })
            },
            //产品页面轮播
            productsSliderItems: (callBack)=> {
                httpOperateForHK.httpGet('/api/facade/fashview/pc/product', (result)=> {
                    let sliderItems;
                    if (result.resultCode == '200') {
                        sliderItems = result.result;
                        store.dispatch(actions.receiveTab1SliderItems(sliderItems));
                    }
                    callBack();
                });
            }
            /* other: (callBack)=> {

             let sliderItems = JSON.parse('[{"imgHref":"/images/pc/fixed_banner1_bg.png","href":"#"},{"imgHref":"/images/pc/fixed_banner1_bg.png","href":"#"},{"imgHref":"/images/pc/fixed_banner1_bg.png","href":"#"}]');
             // let regularProfitProducts=JSON.parse('[{"type":0,"typeName":"购买型","productTypes":[{"name":"车融易","profit":"6.0%-8.0%","financingAmount":"500万","surplusAmount":"180万","process":"75%","products":[{"id":"12345","name":"火柴定制一号","profit":"6.1%","term":"30天","surplusCount":"70万","process":"10"},{"id":"12845","name":"火柴定制二号","profit":"6.0%","term":"30天","surplusCount":"200万","process":"50"}]},{"name":"久恒福海","profit":"6.0%-8.25%","financingAmount":"500万","surplusAmount":"180万","process":"43%","products":[{"id":"12345","name":"火柴定制三号","profit":"6.2%","term":"30天","surplusCount":"600万","process":"20"},{"id":"12845","name":"火柴定制四号","profit":"6.3%","term":"30天","surplusCount":"300万","process":"30"}]},{"name":"火柴产品","profit":"6.1%-8.0%","financingAmount":"500万","surplusAmount":"180万","process":"68%","products":[{"id":"12345","name":"火柴定制五号","profit":"6.4%","term":"30天","surplusCount":"100万","process":"80"},{"id":"12845","name":"火柴定制六号","profit":"6.5%","term":"30天","surplusCount":"600万","process":"40"}]}]},{"type":0,"typeName":"预约型","productTypes":[{"name":"泰山系列","profit":"6.1%-8.0%","financingAmount":"500万","surplusAmount":"180万","process":"21%","products":[{"id":"12345","name":"火柴定制七号","profit":"6.6%","term":"30天","surplusCount":"500万","process":"50"},{"id":"12845","name":"火柴定制八号","profit":"6.7%","term":"30天","surplusCount":"400万","process":"60"}]},{"name":"中融信托","profit":"6.1%-8.0%","financingAmount":"500万","surplusAmount":"180万","process":"68%","products":[{"id":"12345","name":"火柴定制九号","profit":"6.8%","term":"30天","surplusCount":"700万","process":"70"},{"id":"12845","name":"火柴定制十号","profit":"6.9%","term":"30天","surplusCount":"800万","process":"50"}]}]}]');
             store.dispatch(actions.receiveTab1SliderItems(sliderItems));
             // store.dispatch(actions.receiveRegularProfitProducts(regularProfitProducts));
             callBack();
             }*/
        },
        (err, results)=> {

            var regularProfitProducts = [];
            var floatProfitProducts = [];
            var regularAndFloatProfitProducts = [];
            if (results.regularProfitProducts_1 != undefined) {
                regularProfitProducts.push(results.regularProfitProducts_1);
            }
            if (results.regularProfitProducts_2 != undefined) {
                regularProfitProducts.push(results.regularProfitProducts_2);
            }
            if (results.regularProfitProducts_3 != undefined) {
                regularProfitProducts.push(results.regularProfitProducts_3);
            }
            if (results.floatProfitProducts_1 != undefined) {
                floatProfitProducts.push(results.floatProfitProducts_1);
            }
            if (results.floatProfitProducts_2 != undefined) {
                floatProfitProducts.push(results.floatProfitProducts_2);
            }
            if (results.floatProfitProducts_3 != undefined) {
                floatProfitProducts.push(results.floatProfitProducts_3);
            }
            if (results.regularAndFloatProfitProducts_1 != undefined) {
                regularAndFloatProfitProducts.push(results.regularAndFloatProfitProducts_1);
            }
            if (results.regularAndFloatProfitProducts_2 != undefined) {
                regularAndFloatProfitProducts.push(results.regularAndFloatProfitProducts_2);
            }
            if (results.regularAndFloatProfitProducts_3 != undefined) {
                regularAndFloatProfitProducts.push(results.regularAndFloatProfitProducts_3);
            }
            /*for (var item in results) {
             if (results[item] !== undefined) {
             regularProfitProducts.push(results[item]);
             }
             }*/
            store.dispatch(actions.receiveRegularProfitProducts(regularProfitProducts));
            store.dispatch(actions.receiveFloatProfitProducts(floatProfitProducts));
            store.dispatch(actions.receiveRegularAndFloatProfitProducts(regularAndFloatProfitProducts));
            if (renderCallBack) {
                var modelRender = new ModelRender();
                var main = reactDom.renderToString(
                    <Provider store={store}>
                        <HkfsProducts/>
                    </Provider>
                );
                var initializeStore = JSON.stringify(store.getState());
                renderCallBack(modelRender.headerRender(), modelRender.barRender(), modelRender.footerRender(), main, initializeStore);
            }
        });

};